package cn.topcodes.tcsf.admin.scheduling;

import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.PostConstruct;

/**
 * 抽象计划任务
 */
public abstract class AbstractTask implements BeanNameAware {

    private String beanName;

    @Autowired
    private ScheduleService scheduleService;

    @PostConstruct
    public void init() {
        ScheduleJob scheduleJob = new ScheduleJob();
        scheduleJob.setBeanId(beanName);
        scheduleJob.setMethodName("run");
        scheduleJob.setIsConcurrent(isConcurrent());
        scheduleJob.setParamTypes(new Class[0]);
        scheduleJob.setJobName(getJobName());
        scheduleJob.setJobGroup(getGroupName());
        scheduleJob.setParams(new Object[0]);
        scheduleJob.setCronExpression(getCron());
        scheduleJob.setJobStatus(runNow() ? ScheduleJob.STATUS_NORMAL : ScheduleJob.STATUS_PAUSED);
        scheduleService.addJob(scheduleJob);
    }

    @Override
    public void setBeanName(String name) {
        this.beanName = name;
    }

    /**
     * 任务名
     * @return
     */
    protected abstract String getJobName();

    /**
     * 任务组名
     * @return
     */
    protected abstract String getGroupName();

    /**
     * 是否支持并发
     * @return
     */
    protected boolean isConcurrent() {
        return true;
    }

    /**
     * Cron表达式
     * @return
     */
    protected abstract String getCron();

    /**
     * 立即运行
     * @return
     */
    protected boolean runNow() {
        return true;
    }

    /**
     * 执行方法
     */
    public abstract void run();
}
